<template>
  <div class="app-container">
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input placeholder="输入关键字进行过滤" clearable size="mini" suffix-icon="el-icon-search"
                    style="width: 100%;" v-model="filterText"/>
          <div style="max-height:96%;min-height: 96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
            <el-tree
              :default-expanded-keys="defaultExpandedKeys"
              :default-checked-keys="defaultCheckedKeys"
              :default-expand-all="false"
              :data="sheetsTreeList"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="tree"
              node-key="id"
              highlight-current
              v-loading="treeLoading"
              show-checkbox
              @check="onCheck"
            >
              <template #default="{ node, data}">
                <div class="custom-tree-node"
                     style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                  <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                  <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                  <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                  <span class="iconfont icon-dabiao icon-padding"
                        v-if="data.deviceType !== 0 && data.deviceType !== 1 && data.deviceType !== 2"></span>
                  <span>{{ node.label }}</span>
                  <!-- <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span> -->
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>

      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <div style="width: 100%;margin: 10px 0 0 0;">
          <el-row class="line-bottom" v-show="showSearch">
            <el-col class="form_col">
              <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                       :label-width="labelWidth">
                <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                  <el-form-item label="报表类型" prop="frozenType">
                    <el-radio-group v-model="queryParams.frozenType" @change="radioChange">
                      <el-radio-button label="hour">日</el-radio-button>
                      <el-radio-button label="day">月</el-radio-button>
                      <el-radio-button label="month">年</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="日期" prop="freezeTime">
                    <el-date-picker  v-model="queryParams.freezeTime" :type="dateType" :value-format="dateValueFormat" @change="handleDateChange" style="width: 100%" >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="能耗分类" prop="energyUseClassification">
                    <el-select filterable clearable v-model="queryParams.energyUseClassification" placeholder="请选择" style="width: 100%;"
                    @change="(val) => changeEnergyUseClassification(val)">
                      <el-option v-for="dict in dict.type.energy_use_classification" :key="dict.value" :label="dict.label"
                                 :value="parseInt(dict.value)"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="能耗分项" prop="energyUseItem">
                    <el-select filterable clearable v-model="queryParams.energyUseItem" placeholder="请选择" style="width: 100%;">
                      <el-option v-for="dict in dict.type[energyUseClassification === 1 ? 'energy_use_item' : 'energy_use_item_water']" :key="dict.value" :label="dict.label"
                                 :value="parseInt(dict.value)"></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-form>
            </el-col>
            <el-col class="form_query">
              <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text" size="mini">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
              </el-button>
              <el-button type="primary" @click="handleQuery" size="mini">查询</el-button>
              <el-button @click="resetQuery" size="mini">重置</el-button>
              <RightDropdown :queryVisible="false" :columns="columns" class="ml10" :showSearch.sync="showSearch" @export="handleExport" @queryTable="getList" :hasPermiExport="['alarmmanagement:warn:export']"></RightDropdown>
          
            </el-col>
          </el-row>
          <el-table ref="table" key="table" v-loading="loading" :data="dataList" border size="mini" :height="getAvailableHeight" show-summary
                    :default-sort="defaultSort" :tree-props="{children: 'children', hasChildren: 'hasChildren'}" row-key="areaId">
            <template v-for="(item, index) in columns">
              <el-table-column v-if="columns[index].visible" :width="item.width?item.width:100" :label="item.label" :prop="item.prop" :show-overflow-tooltip="true" :align="index===0 ? 'left':'center'" :fixed="item.fixed ? item.fixed : null">
              </el-table-column>
            </template>
          </el-table>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import moment from "moment";
import { getEnergyReportList } from '@/api/datastatistics/meterread/energyReport.js'
export default {
  name: "StatisticsEnergy",
  dicts: ['energy_use_classification','energy_use_item','energy_use_item_water'],
  data() {
    return {
      filterTypeSelect: 'terminalName',
      columnsLabels: [],
      defaultExpandedKeys: [],
      defaultCheckedKeys:[],
      filterText: '',
      // 区域树选项
      sheetsTreeList: [],
      treeLoading: false,
      screenHeight: null,
      formItemSize: 'mini',
      collapseAble: false,
      fold: false,
      maxShow: 4,
      labelWidth: '80px',
      // 列信息
      columns: [],
      // 默认排序
      defaultSort: {prop: 'readDate', order: 'descending'},
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 表格数据
      dataList: [],
      defaultProps: {
        children: "children",
        label: "sheetsName"
      },
      // 查询参数
      queryParams: {
        areaIds: '',
        freezeTime: moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD'),
        frozenType:'hour',
        energyUseClassification:1,
        energyUseItem:null
      },
      energyUseClassification:1,
      // 复选框数据
      checkInfo: {
        length: 0, // 选中个数
        info: [], // 选中的数据
        checkedKeys: [],
      },
      // 验证
      // rules: {
      //   freezeTime:[
      //     { type:"array", required: true, message: '请选择时间范围', trigger: 'change' }
      //   ]
      // }
      dateType:'date',
      dateValueFormat:'yyyy-MM-dd',
    };
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  watch:{
    "dataList":{
      deep:true,
      handler() {
        this.$nextTick(()=>{
          this.$refs.table.doLayout();
        });
      }
    },
    "columns":{
      deep:true,
      handler() {
        this.$nextTick(()=>{
          this.$refs.table.doLayout();
        });
      }
    }
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 175
    },
    userId() {
      return this.$store.state.user.userId
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    }
  },
  mounted() {
    this.getTreeList();
    // this.tip()
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    changeEnergyUseClassification(val) {
      this.energyUseClassification = val
    },
    radioChange(e){
      if(e === 'hour'){//日，显示每天每小时数据
        this.dateType='date';
        this.queryParams.freezeTime = moment().subtract(1,'days').format('YYYY-MM-DD')
        this.dateValueFormat = 'yyyy-MM-dd';
      }else if(e === 'day'){//月，显示每月中每天的数据
        this.dateType='month';
        this.queryParams.freezeTime = moment().subtract(1,'months').format('YYYY-MM')
        this.dateValueFormat = 'yyyy-MM';
      }else{
        //年，显示一年中每月的数据
        this.dateType='year';
        this.queryParams.freezeTime = moment().subtract(1,'years').format('YYYY')
        this.dateValueFormat = 'yyyy';
      }
    },
    // 导出
    handleExport() {
      this.download('energy/report/export', {
        ...this.queryParams
      }, `能耗报表_${new Date().getTime()}.xlsx`)
    },
    // 监听时间变化
    handleDateChange(value) {
      // this.freezeTime = value
      // this.queryParams.freezeTime = [moment(new Date()).subtract(15, 'days').format('YYYY-MM-DD'), moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD')],
      this.queryParams.beginDate = value[0]
      this.queryParams.endDate = value[1]
    },
    onCheck(data, node) {
      let _this = this
      _this.queryParams.areaIds = ''
      let tempInfo1 = node.checkedNodes;
      let tempInfo=tempInfo1.concat(node.halfCheckedNodes);
      if (tempInfo.length === 0) {
        _this.$message.warning('请选择统计区域！');
      }else if (tempInfo.length > 30) {
        _this.checkInfo.info = tempInfo
        _this.$message.warning('最多选择三十个区域！');
      } else {
        _this.checkInfo.info = tempInfo
      }
      if (tempInfo.length > 0 && tempInfo.length <= 30) {
        _this.queryParams.areaIds = tempInfo.map(item=>item.id).join(",");
      }else if(tempInfo.length > 30){
        tempInfo = tempInfo.slice(0, 30)
        _this.queryParams.areaIds = tempInfo.map(item=>item.id).join(",");
      }
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if(!value){
        return true
      }else{
        if(this.filterTypeSelect === 'terminalName'){
          return data.sheetsName.indexOf(value) !== -1;
        }else {
          if(data.deviceType === 3){
            return data.locationNb.indexOf(value) !== -1;
          }
        }
      }
    },
    filteredTreeData(_rawTreeData) {
      // 深拷贝原始数据，避免修改原数据
      const data = JSON.parse(JSON.stringify(_rawTreeData));
      
      // 递归处理数据，只保留两级节点
      const filterNodes = (nodes, level = 1) => {
        return nodes.map(node => {
          // 如果是二级节点，移除它的children
          if (level >= 2) {
            return { ...node, children: undefined };
          }
          // 如果是一级节点，保留children但继续过滤子节点
          if (node.children && node.children.length) {
            return {
              ...node,
              children: filterNodes(node.children, level + 1)
            };
          }
          return node;
        });
      };
      
      return filterNodes(data);
    },

    /** 查询区域树 */
    getTreeList() {
      this.treeLoading = true
      this.sheetsTreeList = JSON.parse(localStorage.getItem('terminalTreeDataLoss'))
      // this.defaultExpandedKeys = [this.sheetsTreeList[0].id];
      // this.defaultCheckedKeys = this.sheetsTreeList.map(item=>item.id);
      if(this.sheetsTreeList.length === 0) {
        this.treeLoading = false;
      }else {
        // this.getList();
        this.treeLoading = false;
      }
    },
    getList() {
      this.dataList = []
      this.loading = true
      if (this.checkInfo.info.length === 0) {
        this.$message.warning('最少选择一个区域！');
        this.loading = false
      } else if (this.checkInfo.info.length > 30) {
        this.$message.warning('最多选择三十个区域！');
        this.loading = false
      } else {
        this.$refs['queryForm'].validate((valid) =>{
          if (valid) {
            getEnergyReportList(this.queryParams)
              .then(res => {
                  this.columns = res.data.columns;
                  this.dataList = res.data.data ? res.data.data : [];
                  this.loading = false
                  this.$nextTick(()=>{
                    this.$refs.table.doLayout();
                  });
              })
              .catch(() => { this.loading = false })
          }
        })
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetChecked()
      this.queryParams = {
        areaIds: '',
        freezeTime: moment(new Date()).subtract(1, 'days').format('YYYY-MM-DD'),
        frozenType:'hour',
        energyUseClassification:1,
        energyUseItem:null
      }
      // this.tip()
    },
    // 清空选中的设备
    resetChecked() {
      this.checkInfo= {
        length: 0, // 选中个数
        info: [], // 选中的数据
        checkedKeys: [],
      };
      this.$refs.tree.setCheckedKeys([]);
    },
    // 提示信息
    tip() {
      this.$message.warning('请选择终端进行查看')
    }
  }
};
</script>
<style scoped lang="scss">
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node {
    width: fit-content;
  }

  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
.el-form-item__error{
  width: 150px;
}
.form_col {
  width: 80%;

  ::v-deep .el-form {

    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 20%;
  }
}

.form_query {
  width: 20%;
  text-align: right;
}
::v-deep .el-table__fixed {
  height: auto !important; // 让固定列的高自适应，且设置!important覆盖ele-ui的默认样式
  bottom: 6px; // 固定列默认设置了定位，
}
</style>
